package cn.microservices.cloud.common.core.validator;

import cn.microservices.cloud.common.core.annotation.CollectionValid;
import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.Objects;


/**
 * 自定义集合类型参数校验器,可对集合类型参数进行校验,目前支持 集合非空,集合元素大小的校验
 * 可在自行拓展
 */
@Component
public class CollectionValidator implements ConstraintValidator<CollectionValid, Collection> {


    /**
     * 集合不能为空的标识,默认值为True
     * 值为Ture将会校验集合是否为空(对象不为空,元素大小>0)
     */
    Boolean notEmpty;

    @Override
    public void initialize(CollectionValid constraintAnnotation) {
        //获取注解属性notEmpty的值
        this.notEmpty = constraintAnnotation.notEmpty();
    }

    @Override
    public boolean isValid(Collection collection, ConstraintValidatorContext context) {
        //开启集合非空校验
        if (notEmpty) {
            return checkCollectionNotEmpty(collection);
        }
        return true;
    }


    private boolean checkCollectionNotEmpty(Collection collection) {
        //集合为空或者集合元素大小小于1
        if (!CollectionUtil.isNotEmpty(collection)) {
            return false;
        }

        //目前只对String类型的元素做校验,可自行拓展
        return collection.stream().noneMatch(e -> (Objects.isNull(e) || StringUtils.isBlank(e.toString())));
    }
}
